<template>
  <div class="login">
    <!-- gutter:间距，单位px -->
    <el-row>
      <el-col :span="8" :offset="8">
        <!-- model:表单的数据 -->
        <!-- rules:表单的检验规则 -->
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()"
              >立即登录</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        username: "admin",
        password: "admin888",
      },
      // 检验规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    submitForm() {
      // this.$refs.ruleForm 找到要检验的表单
      // validate element ui中自带的检验表单的函数
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 表单检验成功
          // 跨域：域名、协议、端口号必须完全一致，否则就是跨域
          this.$http.post('/userlogin', this.ruleForm)
            .then(res => {
              if(res.msg === "登录成功") {
                // 将数据存在vuex中
                this.$store.commit('saveUserInfo', res.list);
                this.$router.push('/');
              }
            })
            .catch(err => {
              console.log(err);
            })
        } else {
          // 表单检验失败
          return false;
        }
      });
    },
  },
};
</script>

<style>
.login {
  width: 100vw;
  height: 100vh;
  background-image: url("../assets/loginbg.jpeg");
  background-size: cover;
}
</style>